package com.tepth.vehiclemaintenance.mvp.main;

import android.content.Intent;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.tepth.vehiclemaintenance.R;
import com.tepth.vehiclemaintenance.adapter.BusListAdapter;
import com.tepth.vehiclemaintenance.base.BaseFragment;
import com.tepth.vehiclemaintenance.bean.User;
import com.tepth.vehiclemaintenance.bean.VehicleMaintain;
import com.tepth.vehiclemaintenance.config.SpKey;
import com.tepth.vehiclemaintenance.config.WorkStatusCode;
import com.tepth.vehiclemaintenance.mvp.work.WorkFragment;
import com.tepth.vehiclemaintenance.tools.DateUtils;
import com.tepth.vehiclemaintenance.tools.SPUtils;
import com.tepth.vehiclemaintenance.tools.ToastUtils;
import com.tepth.vehiclemaintenance.tools.Utils;
import com.tepth.vehiclemaintenance.ui.SettingActivity;
import com.tepth.vehiclemaintenance.ui.view.BadgeView;
import com.tepth.vehiclemaintenance.ui.view.SearchClearEditText;
import com.tepth.vehiclemaintenance.ui.view.datepicker.MonthDateView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

import static com.tepth.vehiclemaintenance.R.id.toolbar;

/**
 * Created by zhangyu on 2017/5/2.
 */

public class MainFragment extends BaseFragment implements MainContract.View,
        SwipeRefreshLayout.OnRefreshListener {
    @BindView(toolbar)
    Toolbar mToolbar;
    @BindView(R.id.et_search)
    SearchClearEditText mEtSearch;
    @BindView(R.id.tv_ready_deal_number)
    BadgeView mTvReadyNumber;
    @BindView(R.id.tv_deal_ing_number)
    BadgeView mTvDealingNumber;
    @BindView(R.id.tv_complete_number)
    BadgeView mTvCompleteNumber;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.tv_group_name)
    TextView mTvGroupName;
    @BindView(R.id.main_date_bar_arrow)
    ImageView mImageViewArrow;
    @BindView(R.id.layout_all)
    LinearLayout mLayoutAll;
    @BindView(R.id.layout_ready_deal)
    LinearLayout mLayoutReadyDeal;
    @BindView(R.id.layout_deal_ing)
    LinearLayout mLayoutDealing;
    @BindView(R.id.layout_complete)
    LinearLayout mLayoutComplete;
    private MainPresenter mMainPresenter;
    private PopupWindow mPopupWindow;
    private MonthDateView monthDateView;
    //未完成日期列表
    private SparseArray<List<Integer>> mSparseArrayNotFinish = new SparseArray<>();
    //当前选中时间
    private String mCurrentDate;
    private BusListAdapter mBusListAdapter;
    private List<VehicleMaintain> mListAll = new ArrayList<>();
    private List<VehicleMaintain> mListReady = new ArrayList<>();
    private List<VehicleMaintain> mListDoing = new ArrayList<>();
    private List<VehicleMaintain> mListComplete = new ArrayList<>();
    private int mCurrentType = 0;
    private User mUser;
    private SweetAlertDialog pDialog;
    private VehicleMaintain mVehicleMaintain;

    public static MainFragment newInstance() {
        Bundle args = new Bundle();
        MainFragment fragment = new MainFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setPresenter() {
        mMainPresenter = new MainPresenter();
        MainModel mainModel = new MainModel();
        mMainPresenter.setVM(this, mainModel);
    }

    @Override
    protected void unbindPresenter() {
        mMainPresenter.onDestroy();
    }

    @Override
    protected void initView(View view) {
        _mActivity.setSupportActionBar(mToolbar);
        //初始化搜索框
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_search:
                        onSearch();
                        break;
                    case R.id.menu_setting:
                        startActivity(new Intent(_mActivity, SettingActivity.class));
                        break;
                }
                return true;
            }
        });
        setHasOptionsMenu(true);
        mEtSearch.setInputType(InputType.TYPE_CLASS_NUMBER);
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearch();
                    Utils.hideInputMethod(v);
                    return true;
                }
                return false;
            }
        });
        mEtSearch.addOnClearListener(new SearchClearEditText.OnClearListener() {
            @Override
            public void onClear() {
                Utils.hideInputMethod(mEtSearch);
                onRefresh();
            }
        });
        mCurrentDate = DateUtils.getNowCalendar(0);
        mTvDate.setText(mCurrentDate);
        if (!initUserInfo()) {
            return;
        }
        initNumber();
        initRecyclerView();
    }

    private boolean initUserInfo() {
        mUser = (User) SPUtils.getObject(_mActivity, SpKey.KEY_USER_INFO);
        if (mUser == null) {
            ToastUtils.showToast(_mActivity, "用户信息获取失败，请重新登录");
            return false;
        }
        mTvGroupName.setText(mUser.getPersonName());
        return true;
    }

    private void onSearch() {
        String keyword = mEtSearch.getText().toString().trim();
        if (!keyword.isEmpty()) {
            ArrayList<VehicleMaintain> list = new ArrayList<>();
            for (VehicleMaintain v : mListAll) {
                if (v.getVehicleNumber().contains(keyword)) {
                    list.add(v);
                }
            }
            showList(list);
        }
    }

    private void initNumber() {
        mTvReadyNumber.setBackground(15, getResources().getColor(R.color.vehicle_yellow));
        mTvDealingNumber.setBackground(15, getResources().getColor(R.color.vehicle_red));
        mTvCompleteNumber.setBackground(15, getResources().getColor(R.color.vehicle_green));
        mTvReadyNumber.setHideOnNull(false);
        mTvDealingNumber.setHideOnNull(false);
        mTvCompleteNumber.setHideOnNull(false);
    }

    private void initRecyclerView() {
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mBusListAdapter = new BusListAdapter(_mActivity,
                R.layout.item_bus_info, new ArrayList<VehicleMaintain>());
        mBusListAdapter.setEmptyView(R.layout.view_empty, (ViewGroup) mRecyclerView.getParent());
        mBusListAdapter.setLoadMoreView(new LoadMoreView() {
            @Override
            public int getLayoutId() {
                return R.layout.view_load_more;
            }

            @Override
            protected int getLoadingViewId() {
                return R.id.load_more_loading_view;
            }

            @Override
            protected int getLoadFailViewId() {
                return R.id.load_more_load_fail_view;
            }

            @Override
            protected int getLoadEndViewId() {
                return R.id.load_more_load_end_view;
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {

            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                mVehicleMaintain = (VehicleMaintain) adapter.getItem(position);
                switch (mVehicleMaintain.getWorkStatusCode()) {
                    case WorkStatusCode.UNDER_PLAN:
                        // AlarmInfoActivity.startActivity(getActivity(), busInfo);
                        break;
                    case WorkStatusCode.READY_WORK:
                        pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("待处理")
                                .setContentText("开始保养？")
                                .setConfirmText("确认")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        //TODO 这个逻辑应该属于fragment后期在看咋处理
                                        //  RepairActivity.startActivity(getActivity(), busInfo);
                                        //OkBus.getInstance().onEvent(HomeActivity.REGISTER_CODE_CONFIRM_REPAIR, busInfo);
                                        //pDialog.dismiss();
                                        mMainPresenter.startWork();
                                        pDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
                                        pDialog.setTitleText("正在提交");
                                        pDialog.setContentText("");
                                        pDialog.showCancelButton(false);
                                    }
                                })
                                .setCancelText("取消");
                        pDialog.setCancelable(false);
                        pDialog.show();
                        break;
                    case WorkStatusCode.UNDER_WORK:
                        // RepairActivity.startActivity(getActivity(), true, busInfo);
                        start(WorkFragment.newInstance(mVehicleMaintain));
                        break;
                    case WorkStatusCode.FINISH_WORK:
                    case WorkStatusCode.COMPLETE_WORK:
                    case WorkStatusCode.FINISH_PLAN:
                        // RepairActivity.startActivity(getActivity(), false, busInfo);
                        start(WorkFragment.newInstance(mVehicleMaintain));
                        break;
                }
            }
        });
        mRecyclerView.setAdapter(mBusListAdapter);
        onRefresh();
        mMainPresenter.getNotFinishList();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onNetworkError(String msg) {
        mSwipeRefreshLayout.setRefreshing(false);
        changeDialogError(msg);
    }

    @Override
    public void onError(String msg) {
        mSwipeRefreshLayout.setRefreshing(false);
        changeDialogError(msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        mSwipeRefreshLayout.setRefreshing(false);
        changeDialogError(msg);
    }

    private void changeDialogError(String msg) {
        if (pDialog != null) {
            pDialog.setTitleText(msg)
                    .setConfirmText("确定")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                        }
                    })
                    .changeAlertType(SweetAlertDialog.ERROR_TYPE);
        }
    }

    @Override
    public String getAuthKey() {
        return mUser.getAuthKey();
    }

    @Override
    public String getStartTime() {
        return DateUtils.getSpecifiedDayAfter(mCurrentDate, 0);
    }

    @Override
    public String getStartDate() {
        return DateUtils.getBeforeMonthCalendar(-3);
    }

    @Override
    public String getEndDate() {
        return DateUtils.getNowCalendar(0);
    }

    @Override
    public String getEndTime() {
        return DateUtils.getSpecifiedDayAfter(mCurrentDate, 1);
    }

    @Override
    public int getMaintenanceId() {
        return mVehicleMaintain.getId();
    }

    @Override
    public void showList(ArrayList<VehicleMaintain> list) {
        mListAll.clear();
        mListReady.clear();
        mListDoing.clear();
        mListComplete.clear();
        //TODO 过滤数据
        if (list != null && !list.isEmpty()) {
            for (VehicleMaintain vehicleMaintain : list) {
                String code = vehicleMaintain.getWorkStatusCode();
                switch (code) {
                    case WorkStatusCode.UNDER_WORK:
                        mListDoing.add(vehicleMaintain);
                        break;
                    case WorkStatusCode.FINISH_WORK:
                    case WorkStatusCode.COMPLETE_WORK:
                        mListComplete.add(vehicleMaintain);
                        break;
                    default:
                        mListReady.add(vehicleMaintain);
                        break;
                }
            }
            mListAll.addAll(list);
        }
        //设置数量
        mTvReadyNumber.setBadgeCount(mListReady.size());
        mTvDealingNumber.setBadgeCount(mListDoing.size());
        mTvCompleteNumber.setBadgeCount(mListComplete.size());
        selectedType(mCurrentType);
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void showNotFinishWorkDates(ArrayList<String> list) {
        if (list != null) {
            mSparseArrayNotFinish = DateUtils.getDateFromMonthArrayList(list);
        }
    }

    @Override
    public void workSucceed() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.cancel();
        }
        onRefresh();
    }

    private void selectedType(int position) {
        mCurrentType = position;
        switch (position) {
            case 0:
                mLayoutAll.setBackgroundColor(getResources().getColor(R.color.color_white));
                mLayoutReadyDeal.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutDealing.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutComplete.setBackgroundColor(getResources().getColor(R.color.white));
                mBusListAdapter.setNewData(mListAll);
                break;
            case 1:
                mLayoutAll.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutReadyDeal.setBackgroundColor(getResources().getColor(R.color.color_white));
                mLayoutDealing.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutComplete.setBackgroundColor(getResources().getColor(R.color.white));
                mBusListAdapter.setNewData(mListReady);
                break;
            case 2:
                mLayoutAll.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutReadyDeal.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutDealing.setBackgroundColor(getResources().getColor(R.color.color_white));
                mLayoutComplete.setBackgroundColor(getResources().getColor(R.color.white));
                mBusListAdapter.setNewData(mListDoing);
                break;
            case 3:
                mLayoutAll.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutReadyDeal.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutDealing.setBackgroundColor(getResources().getColor(R.color.white));
                mLayoutComplete.setBackgroundColor(getResources().getColor(R.color.color_white));
                mBusListAdapter.setNewData(mListComplete);
                break;
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @OnClick({R.id.layout_all, R.id.layout_ready_deal, R.id.layout_deal_ing, R.id.layout_complete})
    public void onTypeChange(View view) {
        switch (view.getId()) {
            case R.id.layout_all:
                selectedType(0);
                break;
            case R.id.layout_ready_deal:
                selectedType(1);
                break;
            case R.id.layout_deal_ing:
                selectedType(2);
                break;
            case R.id.layout_complete:
                selectedType(3);
                break;
        }
    }

    @OnClick(R.id.layout_date)
    public void onDateShow(View view) {
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(_mActivity);
            View contentView = LayoutInflater.from(_mActivity)
                    .inflate(R.layout.view_popwindow_date, null);
            initDateView(contentView);
            mPopupWindow.setContentView(contentView);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    setArrow(R.drawable.ic_arrow_drop_down_black_24dp);
                    String selectDate = monthDateView.getmSelYear() +
                            "-" + DateUtils.addZeroForNum((monthDateView.getmSelMonth() + 1) +
                            "", 2) + "-" + DateUtils.addZeroForNum(monthDateView.getmSelDay() +
                            "", 2);
                    if (!selectDate.equals(mCurrentDate)) {
                        mCurrentDate = selectDate;
                        //TODO 更新列表
                        mTvDate.setText(selectDate);
                        onRefresh();
                    }
                }
            });
            DisplayMetrics dm = getResources().getDisplayMetrics();
            int screenHeight = dm.heightPixels;
            int screenWidth = dm.widthPixels;
            mPopupWindow.setWidth(screenWidth);
            mPopupWindow.setHeight(screenHeight / 3);
            mPopupWindow.setBackgroundDrawable(new PaintDrawable());
        }
        mPopupWindow.showAsDropDown(view);
        setArrow(R.drawable.ic_arrow_drop_up_black_24dp);
    }

    /**
     * 设置箭头
     *
     * @param resId 资源id
     */
    private void setArrow(int resId) {
        VectorDrawableCompat drawable = VectorDrawableCompat.create(getResources(),
                resId, _mActivity.getTheme());
        mImageViewArrow.setImageDrawable(drawable);
    }

    @Override
    public void onRefresh() {
        mMainPresenter.onDestroy();
        mSwipeRefreshLayout.setRefreshing(true);
        mMainPresenter.getMainList();
    }

    private void initDateView(View contentView) {
        List<Integer> list = new ArrayList<>();

        ImageView barDate_left = (ImageView) contentView.findViewById(R.id.bardate_left);
        ImageView barDate_right = (ImageView) contentView.findViewById(R.id.bardate_right);
        TextView barDate_tv = (TextView) contentView.findViewById(R.id.date_text);
        TextView barDate_today = (TextView) contentView.findViewById(R.id.tv_today);
        monthDateView = (MonthDateView) contentView.findViewById(R.id.monthDateView);
        monthDateView.setTextView(barDate_tv);
        monthDateView.setDaysHasThingList(list);
        monthDateView.setDateClick(new MonthDateView.DateClick() {

            @Override
            public void onClickOnDate() {
                if (monthDateView.getmSelDay() == 0)
                    return;
                String tempDate = monthDateView.getmSelYear() + "-" + DateUtils.addZeroForNum((monthDateView.getmSelMonth() + 1) + "", 2) + "-" + DateUtils.addZeroForNum(monthDateView.getmSelDay() + "", 2);
                if (!tempDate.equals(mCurrentDate)) {
                    mCurrentDate = tempDate;
                    onRefresh();
                }
                mTvDate.setText(mCurrentDate);
                mPopupWindow.dismiss();

            }
        });
        barDate_left.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                monthDateView.onLeftClick();
                List<Integer> list = new ArrayList<>();
                if (mSparseArrayNotFinish.size() > 0) {
                    list = mSparseArrayNotFinish.get(monthDateView.getmSelMonth() + 1);
                }

                monthDateView.setDaysHasThingList(list);
            }
        });

        barDate_right.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                monthDateView.onRightClick();
                List<Integer> list = new ArrayList<>();
                if (mSparseArrayNotFinish.size() > 0) {
                    list = mSparseArrayNotFinish.get(monthDateView.getmSelMonth() + 1);
                }
                monthDateView.setDaysHasThingList(list);
            }
        });

        barDate_today.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                monthDateView.setTodayToView();
                List<Integer> list = new ArrayList<>();
                if (mSparseArrayNotFinish.size() > 0) {
                    int month = DateUtils.getNowMonth();
                    list = mSparseArrayNotFinish.get(month);
                }
                monthDateView.setDaysHasThingList(list);
            }
        });
    }
}
